package com.test.netty.ws;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * TextWebSocketFrame: 表示一个文本帧(frame)
 */
@Component
@ChannelHandler.Sharable
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器收到消息: "+msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间： "+ LocalDateTime.now()));
    }

    /**
     * 连接时触发
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id表示唯一的值， LongText是唯一的, ShortText不是唯一的
        //System.out.println("handlerAdded 长id: "+ ctx.channel().id().asLongText());
        //System.out.println("handlerAdded 短id: "+ ctx.channel().id().asShortText());
        Channel channel = ctx.channel();
        channelGroup.add(channel);
        System.out.println("当前在线人数: "+channelGroup.size());

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved 长id: "+ ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
